package com.arnold.www.threadlocal;

/**
 * @ClassName ThreadLocalTest
 * @Description: ThreadLocal应用分析
 * @Author Arnold
 * @Date 2020/4/8
 * @Version V2.0
 **/
public class ThreadLocalTest {
    //初始化值的时候预防空指针异常
    private ThreadLocal<Integer> count = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 1;
        }
    };

    public int getNext(){
        Integer i = count.get();
        i++;
        count.set(i);
        return i;
    }

    public static void main(String[] args){
        final ThreadLocalTest threadLocalTest =new ThreadLocalTest();
        //模拟多线程来ThreadLocal取数据
        new Thread(new Runnable() {
            public void run() {
                while (true){
                    System.out.println(Thread.currentThread().getName()+"\t"+threadLocalTest.getNext());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
        //模拟多线程来ThreadLocal取数据
        new Thread(new Runnable() {
            public void run() {
                while (true){
                    System.out.println(Thread.currentThread().getName()+"\t"+threadLocalTest.getNext());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }
}